package com.itheima.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.service.Impl.UserServiceImpl;
import com.itheima.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * 抽取servlet
 */

public class BaseServlet extends HttpServlet {

    public UserService userService;
    public ObjectMapper obj;
    public void init() throws ServletException {
        userService=new UserServiceImpl();
        obj=new ObjectMapper();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /**
         * 获取uri得到字符串
         * 切割字符串获得方法名
         */
        String uri = req.getRequestURI();
        String methodName = uri.substring(uri.lastIndexOf("/") + 1);
        /**
         * 反射获得方法对象
         * 暴力反射
         * 调用方法执行
         */
        try {
            Method method = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            method.setAccessible(true);
            method.invoke(this,req,resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
